package com.wnhz.work.jy.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.solidfire.gson.Gson;
import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.MyMain;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.bean.ShoppingBean;
import com.wnhz.work.jy.fragment.AlipayBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.alipay.PayResult;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * ---支付方式
 */
public class PayActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "PayActivity";
    private static final int PAY_PASSWORD = 147;
    private TextView title;
    private ImageView iv_pay_wei;
    private ImageView iv_pay_zhi;
    private ImageView iv_pay_yue;
    private ImageView iv_pay_xianxia;

    private TextView tv_pay_money;
    //    private String jump;
    private String allprice;
    private String obtainType;//配送方式
    private String goodsId;//购物车id
    private String addressId;

    private ArrayList<ShoppingBean> list;

    private String orderid;
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        initData();
        initView();
    }

    private void initData() {
        //list = (ArrayList<ShoppingBean>) getIntent().getSerializableExtra("list");
        //obtainType = getIntent().getStringExtra("obtainType");
        //goodsId = getIntent().getStringExtra("goodsId");
//        jump = getIntent().getStringExtra("jump");
        allprice = getIntent().getStringExtra("allprice");
        //addressId = getIntent().getStringExtra("addressId");
        orderid = getIntent().getStringExtra("orderid");
        type = getIntent().getIntExtra("type",-1);
    }

    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("支付");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
//        findViewById(R.id.rl_wei).setOnClickListener(this);
        findViewById(R.id.rl_zhi).setOnClickListener(this);
        findViewById(R.id.rl_surplus).setOnClickListener(this);
//        findViewById(R.id.rl_offline).setOnClickListener(this);
        findViewById(R.id.tv_pay_true).setOnClickListener(this);

        tv_pay_money = (TextView) findViewById(R.id.tv_pay_money);

        iv_pay_wei = (ImageView) findViewById(R.id.iv_pay_wei);
        iv_pay_zhi = (ImageView) findViewById(R.id.iv_pay_zhi);
        iv_pay_yue = (ImageView) findViewById(R.id.iv_pay_yue);
        iv_pay_xianxia = (ImageView) findViewById(R.id.iv_pay_xianxia);

        tv_pay_money.setText(allprice);
    }

    private int payId = 1;
    private String aprice;
    private String paytype;
    private String reward;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                showDialogv7("确定要离开支付页面吗？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                break;

            //余额
           /* case R.id.rl_surplus:
                payId = 5;
                iv_pay_wei.setImageResource(R.mipmap.ic_xuanze_nor);
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze_nor);
                iv_pay_yue.setImageResource(R.mipmap.ic_xuanze31_li3x);
                iv_pay_xianxia.setImageResource(R.mipmap.ic_xuanze_nor);

                break;*/

           /* //微信支付
            case R.id.rl_wei:
                payId = 2;
                iv_pay_wei.setImageResource(R.mipmap.ic_xuanze31_li3x);
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_yue.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_xianxia.setImageResource(R.mipmap.ic_xuanze_nor3x);
                break;*/

            //支付宝
            case R.id.rl_zhi:
                payId = 1;
                iv_pay_wei.setImageResource(R.mipmap.ic_xuanze_nor);
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze31_li);
                iv_pay_yue.setImageResource(R.mipmap.ic_xuanze_nor);
                iv_pay_xianxia.setImageResource(R.mipmap.ic_xuanze_nor);
                break;

           /* //线下
            case R.id.rl_offline:
                payId = 7;
                iv_pay_wei.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_yue.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_xianxia.setImageResource(R.mipmap.ic_xuanze31_li3x);
                break;*/

            //确认支付
            case R.id.tv_pay_true:
                if (payId == 5) {
                    if ("1".equals(MyApplication.getInstance().userBean.getPayPassword())){
                        Intent intent = new Intent(PayActivity.this, InPutPayPassWordActivity.class);
                        //intent.putExtra("orderid", orderid);
                        intent.putExtra("type",2);
                        startActivityForResult(intent,PAY_PASSWORD);
                    }else {
                        showDialogv7(R.string.pay_toast, "取消", "去设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(PayActivity.this,PayPasswordActivity.class));
                            }
                        });
                    }

                }else if (payId == 1){
                    pay();
                }
                break;

            default:
                break;
        }
    }

    private void pay() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("orderId", orderid);
        map.put("payType", payId);
        if (payId == 5){
            map.put("paypass", passwork);
        }
        showDialog();
        XUtil.Post(ConfigUtil.PAY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: "+result);
                try {
                    JSONObject json = new JSONObject(result);
                    String re = json.optString("result");
                    String info = json.optString("info");

                    if (payId == 5){
                        String allprice = json.optString("allprice");
                        String paytype = json.optString("paytype");
                        String reward = json.optString("reward");

                        if ("1".equals(re)) {
                            MyApplication.getInstance().upUser();
                            Intent intent = new Intent(PayActivity.this, SuccessPayActivity.class);
                            intent.putExtra("allprice", allprice);
                            intent.putExtra("paytype", paytype);
                            intent.putExtra("reward", reward);
                            intent.putExtra("type",type);
                            startActivity(intent);
                            Toast.makeText(PayActivity.this, info, Toast.LENGTH_SHORT).show();
                            finish();
                        } else  {
                            Toast.makeText(PayActivity.this, info, Toast.LENGTH_SHORT).show();
                        }
                    }else if (payId == 1){
                        if ("1".equals(re)){
                            AlipayBean bean = new AlipayBean();
                            bean = new Gson().fromJson(info,AlipayBean.class);
                            Log.e(TAG, "onSuccess: "+bean.toString());
                            aprice = json.optString("allprice");
                            paytype = json.optString("paytype");
                            reward = json.optString("reward");
                            setset(bean);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }


    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {

                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PayActivity.this, SuccessPayActivity.class);
                        intent.putExtra("allprice", aprice);
                        intent.putExtra("paytype", paytype);
                        intent.putExtra("reward", reward);
                        intent.putExtra("type",type);
                        startActivity(intent);
                        finish();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(PayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误

                            Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            //startActivity(new Intent(PayActivity.this, MyMain.class).putExtra("Pagination", 3));

                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    public void finish() {
        if (type == -1){
            startActivity(new Intent(PayActivity.this,MyMain.class).putExtra("Pagination",3));
        }else {
            super.finish();
        }

    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    private void setset(AlipayBean alipayBean) {

        String orderInfo = getOrderInfo3(alipayBean);
        // String orderInfo = alipayBean.getStr();
        /**
         * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
         */
        String sign = alipayBean.getSign();
		/*String sign = sign(orderInfo);
		try {
			*//**
         * 仅需对sign 做URL编码
         *//*
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
        /**
         * 完整的符合支付宝参数规范的订单信息
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {

                // 构造PayTask 对象
                PayTask alipay = new PayTask(PayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);


                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private String getOrderInfo3(AlipayBean alipayBean) {
        // 服务接口名称， 固定值 mobile.securitypay.pay
        // 参数编码， 固定值
        String orderInfo = "_input_charset=\"utf-8\"";
        // 商品详情
        orderInfo += "&body=" + "\"" + alipayBean.getBody() + "\"";
        // 服务器异步通知页面路径-----TODO 修改异步通知的地址
        orderInfo += "&notify_url=" + "\"" + alipayBean.getNotify_url() + "\"";
        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + alipayBean.getOut_trade_no()
                + "\"";
        // 签约合作者身份ID
        orderInfo += "&partner=" + "\"" + alipayBean.getPartner() + "\"";
        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";
        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alipayBean.getSeller_id() + "\"";

        orderInfo += "&service=\"mobile.securitypay.pay\"";
        // 商品名称
        orderInfo += "&subject=" + "\"" + alipayBean.getSubject() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + alipayBean.getTotal_fee() + "\"";

        return orderInfo;
    }

    private String passwork;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case PAY_PASSWORD:
                if (resultCode == RESULT_OK){
                    passwork = data.getStringExtra("passwork");
                    pay();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
